/**
 * Created by 瑱彬 on 2015/4/9.
 */
var g1;
var paintCarInterval = true;
var alertType = [];
alertType[1] = "断电警告";
alertType[2] = "位移警告";
alertType[3] = "超速警告";
alertType[4] = "振动警告";
var initJustGage = function () {
    g1 = new JustGage({
        id: "g1",
        value: 0,
        min: 0,
        max: 100,
        title: "速度",
        label: "km/h",
        gaugeWidthScale: 0.2,
        startAnimationTime: 2000,
        startAnimationType: ">",
        refreshAnimationTime: 1000,
        refreshAnimationType: "bounce"

    });

};

var initCar = function () {
    cars = carsSelect;
    paintCarInMap(IMEI, refreshFlowPage);

    setInterval("paintCarIfFlagTrue(" + IMEI + ",refreshJustGage)", 1000);

//    afterInitCar();
};

var paintCarIfFlagTrue = function (IMEI, refreshFlowPage) {
    if (paintCarInterval == true) {
        paintCarInMap(IMEI, refreshFlowPage);
    }
};

var clearAndStopPaintCar = function () {
    map.clearOverlays();
    stopPaintCar();
};

var stopPaintCar = function () {
    paintCarInterval = false;
};

var startPaintCar = function () {
    map.clearOverlays();
    map.setZoom(18);
    paintCarInterval = true;
};

var refreshFlowPage = function (car) {
    refreshJustGage(car);
    refreshHistories(car);
    refreshAlert(car);
};

var refreshAlert = function (car) {
    $.get(CONTEXT + '/ajax/alert/getAlerts?carImei=' + car.carImei, function (data) {
        console.log(data);
        $("#alert-table").html("");
        for (var i = 0; i < data.rows.length; i++) {
            $("#alert-table").append("<tr>" +
            "<td id='alert_" + i + "' class='alert_item'><div>" + alertType[data.rows[i].alertType] +
            " 地点：" + data.rows[i].alertPosname +
            "<div style='display: inline-block;float: right;'>—— " + longToString(data.rows[i].alertTime) +
            "</div></div>" +
            "</td>" +
            "</tr>");
        }
        $(".alert_item").on('click', function (event) {
            var index = $(this).attr("id").replace("alert_", "");
            $(".alert_item").removeClass("info");
            $(this).addClass("info");
            showAlertDetail(data.rows[index]);
        });
    });
};


var refreshHistories = function (car) {
    $.get(CONTEXT + '/ajax/history/getHistroies?carImei=' + car.carImei, function (data) {
        console.log(data);
        $("#history-table").html("");
        for (var i = 0; i < data.rows.length; i++) {
            if (data.rows[i].historyDestination == null) {
                continue;
            }
            $("#history-table").append("<tr>" +
            "<td id='history_" + i + "' class='history_item'><div>" + data.rows[i].historyDestination + "<div style='display: inline-block;float: right;'>—— " + longToString(data.rows[i].historyEnd) +
            "</div></div>" +
            "</td>" +
            "</tr>");

        }
        $(".history_item").on('click', function (event) {
            var index = $(this).attr("id").replace("history_", "");
            $(".history_item").removeClass("info");
            $(this).addClass("info");
            showHistoryDetail(data.rows[index]);
        });

    });
};

var refreshJustGage = function (car) {
    g1.refresh(car.gpsooCar.speed);
    $("#address-td").html(car.address);
    focusOnCar(car);
    gpsoo.loadAddress(car.gpsooCar.lng, car.gpsooCar.lat, function (data) {
        car.address = data.address;
        $("#address-td").html(car.address);
    });

    $("#status-td").html(deviceInfoStr[car.gpsooCar.deviceInfo]);
};



var showHistoryDetail = function (history) {
    $.get(CONTEXT + '/ajax/history/getHistoryPositions?historyId=' + history.historyId, function (data) {
        console.log(data);
        clearAndStopPaintCar();
        var p1 = new BMap.Point(history.historyBeginingPosLong, history.historyBeginingPosLat);
        var p2 = new BMap.Point(history.historyDestinationPosLong, history.historyDestinationPosLat);

        var opts1 = {
            position: p1,    // 指定文本标注所在的地理位置
            offset: new BMap.Size(20, -50)    //设置文本偏移量
        };

        var opts2 = {
            position: p2,    // 指定文本标注所在的地理位置
            offset: new BMap.Size(20, -50)    //设置文本偏移量
        };
        var labels = [];
        var labelStyle = {
            color: "black",
            fontSize: "12px",
            maxWidth: "none",
            borderColor: "#aaa",
            padding: "3px"
        };
        labels[0] = new BMap.Label(longToString(history.historyStart, "yyyy-MM-dd HH:mm:ss") + "<br />"
        + history.historyBegining, opts1);  // 创建文本标注对象
        labels[0].setStyle(labelStyle);


        labels[1] = new BMap.Label(longToString(history.historyEnd, "yyyy-MM-dd HH:mm:ss") + "<br />"
        + history.historyDestination, opts2);  // 创建文本标注对象
        labels[1].setStyle(labelStyle);
        var labelIndex = 2;

        var driving = new BMap.DrivingRoute(map, {renderOptions: {map: map, autoViewport: true}});
        var waypoints = [];
        for (var i = 0; i < data.rows.length; i++) {
            if (data.rows[i].historyPoslong == history.historyBeginingPosLong ||
                data.rows[i].historyPoslat == history.historyBeginingPosLat ||
                data.rows[i].historyPoslong == history.historyDestinationPosLong ||
                data.rows[i].historyPoslat == history.historyDestinationPosLat) {
                continue;
            }
            var point = new BMap.Point(data.rows[i].historyPoslong, data.rows[i].historyPoslat);
            waypoints[i] = point;

            var hpOpts = {
                position: point,    // 指定文本标注所在的地理位置
                offset: new BMap.Size(20, -50)    //设置文本偏移量
            };

            labels[labelIndex] = new BMap.Label(longToString(data.rows[i].historyPositionTime, "yyyy-MM-dd HH:mm:ss") + "<br />"
            + history.historyPositionPosname, hpOpts);  // 创建文本标注对象
            labels[labelIndex].setStyle(labelStyle);
            labelIndex++;

        }

        driving.search(p1, p2, {waypoints: waypoints});//waypoints表示途经点
        driving.setSearchCompleteCallback(function () {
            for (var i = 0; i < labels.length; i++) {
                map.addOverlay(labels[i]);
            }
        });


    });
};


$(document).ready(function () {
    gpsoo.loadAccesstoken("13823862062", "123456", function () {
        initPage(18);
        initCar();
        initJustGage();
    });
    $(".show-father-container").on('click', function () {
        startPaintCar();
    });
});


